//
//  TransViaOriginalViewController.m
//  GNAPP
//
//  Created by zzp on 2019/1/14.
//  Copyright © 2019年 zzp. All rights reserved.
//

#import "TransViaOriginalViewController.h"
#import <MapKit/MapKit.h>
#import "WPAnnotation.h"
#import <CoreLocation/CoreLocation.h>
#import <FMDB/FMDB.h>
#import "UIView+Utils.h"
#import "MACommonUtils.h"
#include "DestionationAnnotation.h"
#import "Location.h"
static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface TransViaOriginalViewController ()<MKMapViewDelegate,CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource>
{
     BOOL didLocataion;//更新位置后就，不再更新区域
    CLLocation * currentLocation;
    double lastSelectChargeTime;//间隔0.1秒，防止隐藏弹框
    UIView *bottomView;
    UITableView *tableView;
    UILabel *nameLabel;
    UIAlertController *alertview;
}
@property (nonatomic,strong) UIView *   headView;
@property(nonatomic,strong) CLLocationManager *locMgr;
@property (nonatomic,strong) NSMutableArray *viaPositions;
@property (strong, nonatomic)  MKMapView *mapView;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic,strong) NSMutableArray *layers;
@property (nonatomic,strong)  WPAnnotation* currentAnnotation;

// 当前方向箭头图标
@property (nonatomic,strong) MKAnnotationView * userHeadingView;

//用于发送请求给服务器
@property(strong,nonatomic)MKDirections *direct;

@end

@implementation TransViaOriginalViewController
-(CLLocationManager *)locMgr{
    if (_locMgr==nil) {
        _locMgr=[[CLLocationManager alloc]init];
        _locMgr.delegate = self;
    }
    return _locMgr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
 
    if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
        [self.locMgr requestWhenInUseAuthorization];
    }
    _viaPositions=[NSMutableArray array];
    _layers=[NSMutableArray array];
    [self.locMgr startUpdatingHeading];
      [_locMgr startUpdatingLocation];
    self.navigationController.navigationBar.hidden=true;
    [self addHeadView];
    //初始化地图控件。与根视图保持一致
    self.mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, _headView.bottom, self.view.width, self.view.height-_headView.bottom)];
    //显示当前用户的地理位置
    MKCoordinateSpan span=MKCoordinateSpanMake(0.2, 0.2);//越大能显示的越多
    MKCoordinateRegion region=MKCoordinateRegionMake([Location shareLocation].location.coordinate, span);
    [_mapView setRegion:region animated:YES];
    self.mapView.showsUserLocation = true;
    [self.view addSubview:self.mapView];
    //显示用户位置（蓝色发光圆圈），还有None和FollowWithHeading两种，当有这个属性的时候，iOS8第一次打开地图，会自动定位并显示这个位置。iOS7模拟器上不会。
    self.mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //地图模式，默认是standard模式，还有卫星模式satellite和杂交模式Hybrid
    self.mapView.mapType=MKMapTypeStandard;
    
    //设置代理
    self.mapView.delegate=self;
    
    [self initAnnotations];
    [self.mapView addAnnotations:self.annotations];
    [self addDestinationAnno];
    [self addNaviBt];
    [self addCurrentLocBt];
    // Do any additional setup after loading the view.
}
-(void)addCurrentLocBt{
    
    UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(self.view.right-50, _headView.bottom+20, 30, 30)];
    [bt setImage:[UIImage imageNamed:@"gpsStat1"]  forState:UIControlStateNormal];
    [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(changeToCurrentLoc) forControlEvents:UIControlEventTouchUpInside];
    bt.alpha=0.5;
    bt.backgroundColor=[UIColor lightGrayColor];
    [self.view  addSubview:bt];

}
-(void)changeToCurrentLoc{
    if(self.layers.count){
        [self.mapView setVisibleMapRect:[MACommonUtils mapRectForOverlays:self.layers] edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge) animated:YES];
    }else{
        MKCoordinateSpan span=MKCoordinateSpanMake(0.2, 0.2);
        MKCoordinateRegion region=MKCoordinateRegionMake(currentLocation.coordinate, span);
        [self.mapView setRegion:region animated:YES];
    }
}
-(void)addNaviBt{
    UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(20, _headView.bottom+20, 60, 30)];
    [bt setTitle:@"导航" forState:UIControlStateNormal];
    [bt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bt addTarget:self action:@selector(showActionSheet) forControlEvents:UIControlEventTouchUpInside];
    bt.alpha=0.5;
    bt.backgroundColor=[UIColor lightGrayColor];
    [self.view addSubview:bt];
}
-(void)addDestinationAnno{
        DestionationAnnotation *anno1=[[DestionationAnnotation alloc]init];
        anno1.coordinate=CLLocationCoordinate2DMake(_tip.location.latitude, _tip.location.longitude);
        anno1.title=_tip.name;
        anno1.icon=@"endPoint";
        [self.mapView addAnnotation:anno1];

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_locMgr startUpdatingHeading];
 
//    [_locMgr startUpdatingLocation];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_locMgr stopUpdatingHeading];
    self.navigationController.navigationBar.hidden=false;
//    [_locMgr stopUpdatingLocation];
}
-(void)addHeadView{
    
    _headView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 150)];
    _headView.backgroundColor=[UIColor blueColor];
    [self.view addSubview:_headView];
    
    UIButton *backbt=[[UIButton alloc]initWithFrame:CGRectMake(0, 20,80, 44)];
    [backbt setTitle:@"Back" forState:UIControlStateNormal];
    [backbt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [backbt addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [_headView addSubview:backbt];
    
    tableView=[[UITableView alloc]initWithFrame:CGRectMake(80, 30, _headView.width-80-10,_headView.height-10-30) style:UITableViewStylePlain];
    tableView.delegate=self;
    tableView.dataSource=self;
    [_headView addSubview:tableView];
    
}
-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)reNavigation{
    
    [self.mapView removeOverlays:self.layers];
    
    [self.layers removeAllObjects];
    
    WPAnnotation *lastAno;
    for (int index=0; index<self.viaPositions.count; index++) {
        WPAnnotation *anAnno = self.viaPositions[index];
        if(!lastAno){
             [self startNavigationFromCLLocation:currentLocation.coordinate toCLLocation:anAnno.coordinate];
        }else{
            [self startNavigationFromCLLocation:lastAno.coordinate toCLLocation:anAnno.coordinate];
        }
        lastAno=anAnno;
    }
    if(self.viaPositions.count>0){
        [self startNavigationFromCLLocation:lastAno.coordinate toCLLocation:CLLocationCoordinate2DMake(self.tip.location.latitude, self.tip.location.longitude)];
    }else{
         [self startNavigationFromCLLocation:currentLocation.coordinate toCLLocation:CLLocationCoordinate2DMake(self.tip.location.latitude, self.tip.location.longitude)];
    }
}
/**
 *  开始导航
 */
- (void)startNavigationFromCLLocation:(CLLocationCoordinate2D )startLocation toCLLocation:(CLLocationCoordinate2D )endLocation{
    //1,获取用户输入的起点终点
    
    MKPlacemark *fromPlacemark = [[MKPlacemark alloc] initWithCoordinate:startLocation
                                                       addressDictionary:nil];
    
    MKPlacemark *toPlacemark   = [[MKPlacemark alloc] initWithCoordinate:endLocation
                                                       addressDictionary:nil];
    
    MKMapItem *fromItem = [[MKMapItem alloc] initWithPlacemark:fromPlacemark];
    
    MKMapItem *toItem   = [[MKMapItem alloc] initWithPlacemark:toPlacemark];
    
    [self moveWith:fromItem toDestination:toItem];
  
}
//提供两个点，在地图上进行规划的方法
-(void)moveWith:(MKMapItem *)formPlce toDestination:(MKMapItem *)endPlace{
    
    //    创建请求体
    // 创建请求体 (起点与终点)
    MKDirectionsRequest *request = [[MKDirectionsRequest alloc] init];
    
    request.source = formPlce;
    request.destination = endPlace;
    
    self.direct = [[MKDirections alloc]initWithRequest:request];
    
    // 计算路线规划信息 (向服务器发请求)
    [self.direct calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse * _Nullable response, NSError * _Nullable error) {
        
        //获取到所有路线
        NSArray <MKRoute *> *routesArray = response.routes;
        //取出最后一条路线
        MKRoute *rute = routesArray.lastObject;
        
        //路线中的每一步
        NSArray <MKRouteStep *>*stepsArray = rute.steps;
        
        //遍历
        for (MKRouteStep *step in stepsArray) {
            
            [self.mapView addOverlay:step.polyline];
        }
        // 收响应结果 MKDirectionsResponse
        // MKRoute 表示的一条完整的路线信息 (从起点到终点) (包含多个步骤)

    }];
    
    
}
- (void)initAnnotations
{
    self.annotations = [NSMutableArray array];
    
    //1.获得数据库文件的路径
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [path objectAtIndex:0];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MAP" ofType:@"db"];
    NSString *dstPath = [docDirectory stringByAppendingPathComponent:@"MAP.db"];
    NSLog(@"%@",filePath);
    if(![[NSFileManager defaultManager]fileExistsAtPath:dstPath]){
        [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:dstPath error:nil];
    }
    //2.获得数据库
    FMDatabase *db=[FMDatabase databaseWithPath:dstPath];
    
    int count=0;
    //3.打开数据库
    if ([db open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [db executeQuery:@"select field_3, field_12 , field_13 from bb    "];
        FMResultSet *countSet = [db executeQuery:@"select count(*) as aa from bb"];
        
        if([countSet next]){
            count=[countSet intForColumn:@"aa"];
        }
        
        CLLocationCoordinate2D coordinates[count];
        int index=0;
        // 2.遍历结果
        while ([resultSet next]) {
            double  longitude= [resultSet doubleForColumn:@"field_12"];
            double latitude = [resultSet doubleForColumn:@"field_13"];
            NSString * name = [resultSet stringForColumn:@"field_3"];
            CLLocationCoordinate2D newCoordinate =CLLocationCoordinate2DMake(latitude,longitude);
            coordinates[index]=newCoordinate;
            index++;
//                        MKPointAnnotation *a1 = [[MKPointAnnotation alloc] init];
//                        a1.coordinate = newCoordinate;
//                        a1.title      = name;
            
            WPAnnotation *a1=[[WPAnnotation alloc]init];
            a1.coordinate=newCoordinate;
            a1.title=name;
            a1.icon=@"img_map_marker";
            [self.annotations addObject:a1];
            //              NSLog(@"resultSet %lf  %lf", ID, name);
        }
        
        
    }else{
        
        
    }
}
-(void)showBottomViewWithInfo{

    if(!bottomView){
        bottomView=[[UIView alloc]initWithFrame:CGRectMake(0, self.view.bottom-150, self.view.width, 150)];
        bottomView.backgroundColor=[UIColor whiteColor];
        [self.view addSubview:bottomView];
        
        nameLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,bottomView.width, 35)];
        nameLabel.font=[UIFont boldSystemFontOfSize:15.0f];
        nameLabel.textAlignment=NSTextAlignmentCenter;
        nameLabel.textColor=[UIColor redColor];
        [bottomView addSubview:nameLabel];
        [self addLineviewWithFrame:CGRectMake(0, nameLabel.bottom-1, nameLabel.width, 1) onView:nameLabel];
        
        NSArray *titles=@[@"设为途径点",@"查看详细",@"取消"];
        
        
        for (int d=0; d<titles.count; d++) {
            UIButton *bt=[[UIButton alloc]initWithFrame:CGRectMake(0,nameLabel.bottom+(nameLabel.height)*d,bottomView.width, nameLabel.height )];
            [bt setTitle:titles[d] forState:UIControlStateNormal];
            [bt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            bt.titleLabel.font=[UIFont systemFontOfSize:15.0f];
            bt.tag=1000+d;
            [bt addTarget:self action:@selector(setOrCancelVia:) forControlEvents:UIControlEventTouchUpInside];
            [self addLineviewWithFrame:CGRectMake(0, bt.height-1, bt.width, 1) onView:bt];
            [bottomView addSubview:bt];
        }
    }
    UIButton *bt=(UIButton*)[bottomView viewWithTag:1000];
    if([self.viaPositions containsObject:_currentAnnotation]){
        [bt setTitle:@"取消途径点" forState:UIControlStateNormal];
    }else{
        [bt setTitle:@"设为途径点" forState:UIControlStateNormal];
    }
    nameLabel.text=_currentAnnotation.title;
    bottomView.hidden=false;
}
-(void)addLineviewWithFrame:(CGRect)frame onView:(UIView*)view{
    UIView *aView=[[UIView alloc]initWithFrame:frame];
    aView.backgroundColor=[UIColor lightGrayColor];
    [view addSubview:aView];
}
-(void)setOrCancelVia:(UIButton*)bt{
    if(bt.tag==1000){
        if([self.viaPositions containsObject:_currentAnnotation]){
            [self.viaPositions removeObject:_currentAnnotation];
           [self.mapView removeAnnotation:_currentAnnotation];
//            WPAnnotation *a1=[[WPAnnotation alloc] init];
//            _currentAnnotationView.annotation;
            _currentAnnotation.icon=@"img_map_marker";

            [self.mapView addAnnotation:_currentAnnotation];
        }else{
            [self.viaPositions addObject:_currentAnnotation];
//            WPAnnotation *a1=_currentAnnotationView.annotation;
              [self.mapView removeAnnotation:_currentAnnotation];
            _currentAnnotation.icon=@"gpsStat1";
          
            [self.mapView addAnnotation:_currentAnnotation];
        }
        [self reNavigation];
        [self showBottomViewWithInfo];

    }else if(bt.tag==1002){
        bottomView.hidden=true;
    }

        [tableView reloadData];
}
-(void)showActionSheet{
    // 创建
    
    if([alertview isBeingPresented]){
        [alertview dismissViewControllerAnimated:false completion:nil];
        return;
    }
    alertview=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    
    NSArray *titles=@[@"百度地图",@"高德地图"];
    NSArray *urls=@[@"baidumap://",@"iosamap://"];
    
    
    for (int d=0; d<titles.count; d++) {
        if(d<2&&[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urls[d]]]){
            UIAlertAction *defult = [UIAlertAction actionWithTitle:titles[d] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             
                NSMutableArray  *viaPoint=[[NSMutableArray alloc]init];
                if (self.viaPositions.count>0) {
                    for (id<MKAnnotation> anno in self.viaPositions) {
                        NSDictionary *dic=@{@"name":anno.title,@"lat":[NSNumber numberWithDouble: anno.coordinate.latitude],@"lng":[NSNumber numberWithDouble:anno.coordinate.longitude]};
                        [viaPoint addObject:dic];
                    }
                }
                NSDictionary *viaDic=@{@"viaPoints":viaPoint};
                NSError *error = nil;
                NSData *jsonData = [NSJSONSerialization dataWithJSONObject:viaDic
                                                                   options:kNilOptions
                                                                     error:&error];
                
                NSString *jsonString = [[NSString alloc] initWithData:jsonData
                                                             encoding:NSUTF8StringEncoding];
                NSString *urlString;
                if(d==0){
                    urlString = [[NSString stringWithFormat:@"%@map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=%@&mode=driving&coord_type=gcj02&viaPoints=%@",urls[d],self->_tip.location.latitude, self->_tip.location.longitude,self.tip.name,jsonString] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                    
                }else if (d==1){
                    urlString = [[NSString stringWithFormat:@"%@path?sourceApplication=applicationName&sid=BGVIS1&slat=%f&slon=%f&sname=当前位置&did=BGVIS2&dlat=%f&dlon=%f&dname=%@&dev=0&t=0",urls[d],self->currentLocation.coordinate.latitude,self->currentLocation.coordinate.longitude,self->_tip.location.latitude, self->_tip.location.longitude,self.tip.name] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                }
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            }];
            [alertview addAction:defult];
        }
        
    }
   UIAlertAction *appleMapBt = [UIAlertAction actionWithTitle:@"苹果地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        MKPlacemark *fromPlacemark = [[MKPlacemark alloc] initWithCoordinate:self->currentLocation.coordinate
                                                           addressDictionary:[NSDictionary dictionary]];
        
        MKPlacemark *toPlacemark   = [[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(self.tip.location.latitude, self.tip.location.longitude)
                                                           addressDictionary:[NSDictionary dictionary]];
       NSDictionary *options = @{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};
       
       MKMapItem *fromItem = [[MKMapItem alloc] initWithPlacemark:fromPlacemark];
       fromItem.name = @"我的位置";
       MKMapItem *toItem = [[MKMapItem alloc] initWithPlacemark:toPlacemark];
       toItem.name = self.tip.name;
       [MKMapItem openMapsWithItems:@[fromItem,toItem] launchOptions:options];

        
   }];
    [alertview addAction:appleMapBt];
    
    
    UIAlertAction *defult = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self->alertview dismissViewControllerAnimated:YES completion:nil];
    }];
     [alertview addAction:defult];
    
    [self presentViewController:alertview animated:YES completion:nil];
    
    
}
#pragma mark -- CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    if (newHeading.headingAccuracy < 0)  return;
    
    CLLocationDirection heading = newHeading.trueHeading > 0 ? newHeading.trueHeading : newHeading.magneticHeading;
    CGFloat rotation =  heading/180 * M_PI;
    self.userHeadingView.transform = CGAffineTransformMakeRotation(rotation);
}
//- (void)locationManager:(CLLocationManager *)manager
//    didUpdateToLocation:(CLLocation *)newLocation
//           fromLocation:(CLLocation *)oldLocation{
//    currentLocation=newLocation;
//}
#pragma mark MapView Delegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    static NSString *ID=@"annoView";
    MKAnnotationView *annoView=[mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView==nil) {
        annoView=[[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
        //点击大头针出现信息（自定义view的大头针默认点击不弹出）
        annoView.canShowCallout=false;
    }
    //再传递一次annotation模型（赋值）
    annoView.annotation=annotation;
     if([annotation isKindOfClass:[WPAnnotation class]]){
        WPAnnotation *anno=annotation;
        annoView.image=[UIImage imageNamed:anno.icon];
    }else if([annotation isKindOfClass:NSClassFromString(@"MKUserLocation")]){
        annoView.image=[UIImage imageNamed:@"userPosition"];
        _userHeadingView=annoView;
    }else if ([annotation isKindOfClass:[DestionationAnnotation class]]){
        DestionationAnnotation *anno=annotation;
        annoView.image=[UIImage imageNamed:anno.icon];
    }

    return annoView;
}
//-(void)tapMapView:(UITapGestureRecognizer *)tap{
//    //获取点击的点
//    CGPoint point=[tap locationInView:tap.view];
//    //点转换成坐标
//    CLLocationCoordinate2D coordi=[self.mapView convertPoint:point toCoordinateFromView:self.mapView];
//    //创建大头针模型，设置大头针的坐标，然后把大头针加进去
//    MKAnnotationView *anno=[[MKAnnotationView alloc]init];
//
//
//    MKPointAnnotation *a1 = [[MKPointAnnotation alloc] init];
//    a1.coordinate = coordi;
////    a1.title      = name;
////    anno.coordinate=coordi;
//    a1.title=@"拙政园";
//    a1.subtitle=@"苏州市博物馆附近";
//    anno.annotation=a1;
//    [self.mapView addAnnotation:anno];
//}


//MKUserLocation是地图上大头针模型，有title和subtitle以及location信息。该方法调用频繁
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    NSLog(@"%f,%f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude);
    //点击大头针，会出现以下信息

    
    //让地图显示用户的位置（iOS8一打开地图会默认转到用户所在位置的地图），该方法不能设置地图精度
    //    [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    currentLocation=userLocation.location;
    
    if (!didLocataion) {
        //这个方法可以设置地图精度以及显示用户所在位置的地图
        MKCoordinateSpan span=MKCoordinateSpanMake(0.1, 0.1);
        MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
        [mapView setRegion:region animated:YES];

        
        [self startNavigationFromCLLocation:currentLocation.coordinate toCLLocation:CLLocationCoordinate2DMake(self.tip.location.latitude, self.tip.location.longitude)];
        didLocataion=true;
    }
   
 

}

//可以打印经纬度的跨度，用来测试当前视图下地经纬度跨度是多少，然后用于上面的MKCoordinateSpanMake方法中
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"%f,%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}
-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{
    bottomView.hidden=true;
}
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
    NSLog(@"view.annotation.title %@",view.annotation.title);
    self.currentAnnotation=(WPAnnotation*)view.annotation;
    [self showBottomViewWithInfo];
}
// 返回指定的遮盖模型所对应的遮盖视图, renderer-渲染
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay
{
    // 判断类型
    if ([overlay isKindOfClass:[MKPolyline class]]) {
        // 针对线段, 系统有提供好的遮盖视图
        MKPolylineRenderer *render = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        
        // 配置，遮盖线的颜色
        render.lineWidth = 5;
//        render.strokeColor =  [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
        render.strokeColor=[UIColor blueColor];
        [self.layers addObject:overlay];
        return render;
    }

    // 返回nil, 是没有默认效果
    return nil;
}
- (void)mapView:(MKMapView *)mapView didAddOverlayRenderers:(NSArray<MKOverlayRenderer *> *)renderers{
    [self.mapView setVisibleMapRect:[MACommonUtils mapRectForOverlays:self.layers] edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge) animated:YES];
}

#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 30;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  self.viaPositions.count+2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tipCellIdentifier = @"tipCellIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tipCellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:tipCellIdentifier];
    }
    if(indexPath.row==0){
        cell.textLabel.text = @"从：我的位置";
    }else if(indexPath.row== (self.viaPositions.count+1)){
        cell.textLabel.text = [NSString stringWithFormat:@"到：%@",_tip.name];
    }else{
        WPAnnotation *pointItem=self.viaPositions[indexPath.row-1];
        cell.textLabel.text =[NSString stringWithFormat:@"途径：%@", pointItem.title];
    }
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    NSLog(@"%@ dealloc",NSStringFromClass([self class]));
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
